﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using XXX.api.Auth;
using XXX.Bo;
using XXX.Common;

namespace XXX.api.Controllers
{
    [Route("api/oauth")]
    [ApiController]
    public class OAuthController : ControllerBase
    {
        //private readonly ILogger<OAuthController> _logger;
        private readonly ILogger<OAuthController> _logger;
        public OAuthController(ILogger<OAuthController> logger)
        {
            _logger = logger;
            //_generateRefreshToken = generateRefreshToken;
        }

        /// <summary>
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("token")]
        public Models.RetModel2 GetAccessToken(string username, string password)
        {
            Models.RetModel2 retModel = new Models.RetModel2();

            //这儿在做用户的帐号密码校验。我这儿略过了。
            int bCheck = 0;
            if (username == CanShu.apiuser && password == CanShu.apipwd)
            {
                bCheck = 1;
            }

            if (bCheck == 0)
            {
                retModel.code = 101;
                retModel.message = "账号密码不正确";
                return retModel;
            };

            var claims = new[]
            {
        new Claim(ClaimTypes.Name, username),
        new Claim(ClaimTypes.Role, ""),
    };

            _logger.LogInformation($"Current UTC Time: {DateTime.UtcNow}");
            _logger.LogInformation($"Current Time: {DateTime.Now}");

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TokenParameter.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            // 设置token过期时间为1小时后
            var expires = DateTime.Now.AddHours(1);
            var jwtToken = new JwtSecurityToken(
                TokenParameter.Issuer,
                TokenParameter.Audience,
                claims,
                expires: expires,
                signingCredentials: credentials);

            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            _logger.LogInformation($"Token ValidTo: {jwtToken.ValidTo}");

            // 创建返回的token实体对象
            var tokenEntity = new
            {
                AccessToken = token,
                ExpiresIn = (int)(expires - DateTime.Now).TotalSeconds, // 剩余有效秒数
                ExpiresTime = expires.ToString("yyyy-MM-dd HH:mm:ss") // 具体的过期时间
            };

            retModel.code = 200;
            retModel.data = tokenEntity; // 返回包含token和过期时间的对象
            return retModel;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Login")]
        public IActionResult Login(string user, string pwd)
        {
            
                return Ok(new TokenHelper().CreateToken("gly"));
            
        }

        [HttpGet]
        [Authorize]
        [Route("Demo1")]
        public IActionResult Demo1()
        {
            return Ok("1232131");
        }

        [HttpGet]
        [AllowAnonymous]
        [Route("Result")]
        public IActionResult Result(string username,string token, string refresh_token)
        {
            return Ok(new TokenHelper().Refresh(username,token, refresh_token));
        }
 
    }
}
